package com.caiyi.financial.nirvana.sms.filters;

import com.caiyi.financial.nirvana.sms.entity.SmsUser;
import com.caiyi.financial.nirvana.sms.enums.ReturnCodeEnum;
import com.caiyi.financial.nirvana.sms.enums.SmsUserAuditTypeEnum;
import com.caiyi.financial.nirvana.sms.jedis.JedisKey;
import com.caiyi.financial.nirvana.sms.jedis.JedisService;
import com.caiyi.financial.nirvana.sms.param.SendMsgParam;
import com.caiyi.financial.nirvana.sms.util.CommUtil;

import java.util.Set;
import java.util.regex.Pattern;

/**
 * Created by Mario on 2018/2/27 0027.
 * 用户短信模板过滤器
 */
public class TemplateFilter implements Filter {

    @Override
    public void run(FilterChain filterChain) {
        SendMsgParam param = filterChain.getParam();
        SmsUser user = filterChain.getSmsUser();
        boolean codeFree = false;
        if (user.getAuditType() == SmsUserAuditTypeEnum.CODE_FREE.index) {
            codeFree = CommUtil.needFree(param.getContent());
        }
        if (user.getAuditType() == SmsUserAuditTypeEnum.TEMPLATE.index || codeFree) {
            String key = String.format(JedisKey.SMS_TEMPLATE, user.getAccount());
            Set<String> userTemplates = JedisService.smembers(key);
            boolean isMatch = false;
            String content = param.getContent().replaceAll("【.*】", "");
            for (String template : userTemplates) {
                //添加开头结尾
                isMatch = Pattern.matches("^" + template + "$", content);
                if (isMatch) break;
            }
            if (!isMatch) {
                filterChain.setTemplateCode(ReturnCodeEnum.TEMPLATE_ERROR.code);
            }
        }
        filterChain.doFilter();
    }

}
